package com.joysuch.wwyt.licence.bean;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.licence.exception.LicenceException;
import com.joysuch.wwyt.licence.service.impl.LicenceServiceImpl;
import com.joysuch.wwyt.util.AESUtil;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 授权模块黑名单对象
 *
 * @author jialei
 * @date 2022-04-27
 */
@ToString
public class LicenceCacheDto {

    private static final Logger LOGGER = LoggerFactory.getLogger(LicenceCacheDto.class);

    /**
     * 消息体摘要
     */
    private String digest;

    /**
     * licence 状态，900初始化/901授权过期/902授权未到期
     */
    private int state;

    /**
     * licence 状态消息
     */
    private String stateMsg;

    /**
     * 黑名单路由信息
     */
    private Set<String> blackUrlSet;

    public String getDigest() {
        return digest;
    }

    public void setDigest(String digest) {
        this.digest = digest;
    }

    public int getState() {
        if (!isValid()) {
            throw new LicenceException();
        }
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public String getStateMsg() {
        return stateMsg;
    }

    public void setStateMsg(String stateMsg) {
        this.stateMsg = stateMsg;
    }

    public Set<String> getBlackUrlSet() {
        return blackUrlSet;
    }

    public void setBlackUrlSet(Set<String> blackUrlSet) {
        this.blackUrlSet = blackUrlSet;
    }

    /**
     * licence 状态是否有效
     *
     * @return
     */
    @JSONField(serialize = false)
    public boolean isAllow() {
        return 0 == this.state;
    }

    @JSONField(serialize = false)
    public String buildDigest() {
        String digestHex = MD5.create().digestHex(this.state + JSON.toJSONString(this.blackUrlSet) + BaseConfigCodes.LICENCE_AES_KEY, StandardCharsets.UTF_8);
        return digestHex;
    }

    /**
     * 摘要和内容是否匹配
     *
     * @return true匹配/false不匹配
     * @throws LicenceException
     */
    @JSONField(serialize = false)
    public boolean isValid() {
        String sign = this.buildDigest();
        return Objects.equals(this.digest, sign);
    }


    @JSONField(serialize = false)
    public Set<String> getDecryptedBlackUrlSet() {
        if (!isValid() || !isAllow()) {
            throw new LicenceException();
        }
        Set<String> decryptedSet = new HashSet<>();
        if (this.blackUrlSet == null) {
            return decryptedSet;
        }
        for (String blackUrl : this.blackUrlSet) {
            decryptedSet.add(AESUtil.decrypt(blackUrl, BaseConfigCodes.LICENCE_AES_KEY));
        }

        return decryptedSet;
    }
}
